package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jodd.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrGroupDao attrGroupDao;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        // 保存基本数据：属性表
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);

        // 保存关联关系：属性与属性分组表（只有基本属性-1，才有属性分组，才需要保存这个关联）
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils selectAttrByPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", attrType.equalsIgnoreCase("base") ?
                        ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() :
                        ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        // 模糊查询
        String key = (String) params.get("key");
        if (StringUtil.isNotEmpty(key)) {
            wrapper.and(o -> {
                o.eq("attr_id", key).or().like("attr_name", key);
            });
        }


        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> attrEntityList = page.getRecords();
        List<AttrRespVo> attrRespVoList = attrEntityList.stream().map(attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 根据 属性id 查询 属性分组id
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));

            // 基本属性才有分组
            if ("base".equalsIgnoreCase(attrType)) {
                // 查询属性分组名称
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    attrRespVo.setGroupName(attrGroupEntity == null ? null : attrGroupEntity.getAttrGroupName());
                }
            }

            // 查询 分类名称
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            attrRespVo.setCatelogName(categoryEntity == null ? null : categoryEntity.getName());

            return attrRespVo;
        }).collect(Collectors.toList());

        pageUtils.setList(attrRespVoList);

        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        if (attrId == null) {
            return null;
        }

        AttrRespVo respVo = new AttrRespVo();

        // 查询属性
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, respVo);

        // 设值属性分组信息（基础属性 才有 属性分组）
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            respVo.setAttrGroupId(relationEntity == null ? null : relationEntity.getAttrGroupId());
            if (relationEntity != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                respVo.setGroupName(attrGroupEntity == null ? null : attrGroupEntity.getAttrGroupName());
            }
        }

        // 设值分类信息
        Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
        respVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
        respVo.setCatelogName(categoryEntity == null ? null : categoryEntity.getName());

        return respVo;
    }


    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        // 更新属性表
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        // 基础属性 才有 属性分组
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 保存/更新属性与属性分组表
            Long attrId = attr.getAttrId();
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrId);
            relationEntity.setAttrGroupId(attr.getAttrGroupId());

            Integer relationCount = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationCount > 0) {
                // 已有关联数据，则更新
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            } else {
                // 没有关联数据，则保存
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }

    }


    /**
     * 根据分组id 查询 关联的所有基本属性
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttrList(Long attrgroupId) {
        List<AttrEntity> attrEntityList = new ArrayList<>();
        if (attrgroupId == null) {
            return attrEntityList;
        }

        // 查询关联的属性id
        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        if (CollectionUtils.isEmpty(relationEntityList)) {
            return attrEntityList;
        }

        // 查询 属性集合
        List<Long> attrIdList = relationEntityList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(attrIdList)) {
            return attrEntityList;
        }
        attrEntityList = this.baseMapper.selectBatchIds(attrIdList);

        return attrEntityList;
    }

    @Override
    public void deleteRelation(List<AttrGroupRelationVo> voList) {
        if (CollectionUtils.isEmpty(voList)) {
            return;
        }

        List<AttrAttrgroupRelationEntity> relationEntityList = voList.stream().map(o -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(o, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchRelation(relationEntityList);

    }


    /**
     * 查询当前分组没有关联的所有属性，且只能查出当前分组所属分类下的所有属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttrByPage(Map<String, Object> params, Long attrgroupId) {
        if (attrgroupId == null) {
            return null;
        }

        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        // 1、当前分组只能关联自己所属分类里面的所有属性（基础属性）
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if (catelogId != null) {
            wrapper.eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        }

        // 2、当前分组只能关联没有引用的属性
        // 2.1）当前分类下的所有分组
        List<AttrGroupEntity> groupEntityList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        // 2.2）这些分组关联的属性
        List<Long> otherAttrIdList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(groupEntityList)) {
            List<Long> otherAtrrGroupIdList = groupEntityList.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
            List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", otherAtrrGroupIdList));
            if (!CollectionUtils.isEmpty(relationEntityList)) {
                otherAttrIdList = relationEntityList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
            }
        }
        // 2.3）从当前分类的所有属性中移除这些属性
        if (!CollectionUtils.isEmpty(otherAttrIdList)) {
            wrapper.notIn("attr_id", otherAttrIdList);
        }

        // 模糊查询
        String key = (String) params.get("key");
        if (StringUtil.isNotEmpty(key)) {
            wrapper.and(o -> {
                o.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrIdList(List<Long> attrIdList) {
        return baseMapper.selectSearchAttrIdList(attrIdList);
    }


}






























